import json
import logging
import time

from django.contrib import auth
from django.http import HttpResponseRedirect, JsonResponse, HttpResponse
from django.shortcuts import render
# Create your views here.
from rest_framework.views import APIView

from system import models
from system.models import User, userToken
from system.utils import response_success, response_fails


def login(req):
    return render(req, 'login.html')

def index(req):

    return render(req, 'index.html',{'user':'刘平'})


# def dologin(req):
#     if req.method == 'POST':
#         user_name = req.POST.get('user_name')
#         password = req.POST.get('password')
#         user = auth.authenticate(username=user_name, password=password)
#         if user is not None:
#             auth.login(req, user)
#             req.session['user'] = user_name
#             return HttpResponseRedirect('/index.html', locals())
#             # return render(req, 'index.html')
#         else:
#             return render(req, 'login.html', {'error': '用户名或密码错误！'})


def md5(user):
    import hashlib
    import time

    # 当前时间，相当于生成一个随机的字符串
    ctime = str(time.time())

    # token加密
    m = hashlib.md5(bytes(user, encoding='utf-8'))
    m.update(bytes(ctime, encoding='utf-8'))
    return m.hexdigest()


class AuthView(APIView):

    def post(self, request, *args, **kwargs):
        try:
            usr = request.data.get('username')
            pas = request.data.get('password')

            obj = models.User.objects.filter(username=usr, password=pas).first()

            if not obj:
                return response_fails('用户名或者密码错误！')

            token = md5(obj.username)
            models.userToken.objects.update_or_create(username=obj, defaults={'token': token})

            # httpResponse = HttpResponseRedirect('index/')
            httpResponse = HttpResponse(json.dumps({'success': True,'user': obj.username, 'token': token}, ensure_ascii=False))
            httpResponse.set_cookie("token", token, expires=None)
            return httpResponse
            # return  render(request, 'index.html')
        # render(request, 'login.html')

        except Exception as e:
            logging.error(e)
            return response_fails('服务器异常！')
